/*
 * Created by JFormDesigner on Wed Jun 07 14:37:03 CST 2023
 */

package gui.user;

import dao.*;
import entity.*;
import gui.admin.AdminMainFrame;
import gui.admin.tablemodel.ProductCategoryTableModel;
import gui.user.model.CategoryListModel;
import gui.user.model.SaleDetailsTableModel;
import gui.user.model.UserProductModel;
import util.OrderDetailNoUtil;
import util.OrderNoUtil;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.time.LocalDate;
import java.util.List;
import javax.swing.*;

/**
 * @author Liubuzhu
 */
public class BrowseProductFrame extends JFrame {
    ProductCategoryDao productCategoryDao = new ProductCategoryDao();
    ProductDao productDao = new ProductDao();
    public BrowseProductFrame(String userId) throws Exception {
        initComponents(userId);
    }

    private void initComponents(String userId) throws Exception {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        label1 = new JLabel();
        scrollPane1 = new JScrollPane();
        list1 = new JList();
        label2 = new JLabel();
        scrollPane2 = new JScrollPane();
        table1 = new JTable();
        label3 = new JLabel();
        label4 = new JLabel();
        label5 = new JLabel();
        scrollPane3 = new JScrollPane();
        table2 = new JTable();
        label6 = new JLabel();
        quantity = new JTextField();
        label7 = new JLabel();
        productId = new JTextField();
        addProductBtn = new JButton();
        payBtn = new JButton();
        cancelBtn = new JButton();


        SaleDao saleDao = new SaleDao();
        String orderNo = OrderNoUtil.randomOrderCode();//获取随机订单编号
        LocalDate currentDate = LocalDate.now();//获取此时日期
        String saleDate = currentDate.toString();
        Sale sale = new Sale(orderNo,userId,"刘小小",0.0F,saleDate);
        saleDao.addSale(sale);//将订单添加进数据库

        List productCategoryList = productCategoryDao.getAllProductCategory();


        //======== this ========
        setTitle("\u5546\u54c1\u6d4f\u89c8\u9875\u9762");
        setPreferredSize(new Dimension(1275, 650));
        setVisible(true);
        var contentPane = getContentPane();
        contentPane.setLayout(null);

        //---- label1 ----
        label1.setText("\u5546\u54c1\u5206\u7c7b");
        label1.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label1);
        label1.setBounds(45, 35, 105, 45);

        //======== scrollPane1 ========
        {

            //---- list1 ----
            list1.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
            list1.setModel(new CategoryListModel());
            scrollPane1.setViewportView(list1);
        }
        contentPane.add(scrollPane1);
        scrollPane1.setBounds(45, 85, 95, 350);

        //---- label2 ----
        label2.setText("\u5546\u54c1\u4fe1\u606f");
        label2.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label2);
        label2.setBounds(260, 35, 105, 45);

        //给表格添加鼠标点击事件
        list1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //super.mouseClicked(e);
                int index = list1.getSelectedIndex();//获取鼠标当前点击的行下标
                //获取点击商品分类
                ListModel<String> listModel = list1.getModel();
                String productCategoryNameTemp = listModel.getElementAt(index);
                ProductCategory productCategory = (ProductCategory) productCategoryList.get(index);
                try {
                    table1.setModel(new UserProductModel(productCategory.getCategoryId()));
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }

            }
        });

        //======== scrollPane2 ========
        {

            //---- table1 ----
            table1.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
            scrollPane2.setViewportView(table1);
        }
        contentPane.add(scrollPane2);
        scrollPane2.setBounds(140, 85, 310, 350);

        //给表格添加鼠标点击事件
        table1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //super.mouseClicked(e);
                int row = table1.getSelectedRow();//获取鼠标当前点击的行下标
                //获取点击行商品编号
                String productNameTemp = (String) table1.getValueAt(row,0);
                productId.setText(productNameTemp);
                //设置商品图片
                ImageIcon imageIcon = new ImageIcon("./image/product/" + productNameTemp + ".jpg");
                label3.setIcon(imageIcon);
            }
        });


        //---- label3 ----
        label3.setText("                         \u8be5\u5546\u54c1\u6682\u672a\u6709\u56fe\u7247");
        label3.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label3);
        label3.setBounds(450, 85, 350, 350);

        //---- label4 ----
        label4.setText("\u5546\u54c1\u56fe\u7247");
        label4.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label4);
        label4.setBounds(595, 30, 105, 45);

        //---- label5 ----
        label5.setText("\u8d2d\u7269\u8f66");
        label5.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label5);
        label5.setBounds(975, 30, 105, 45);

        //======== scrollPane3 ========
        {
            scrollPane3.setViewportView(table2);
        }
        contentPane.add(scrollPane3);
        scrollPane3.setBounds(790, 85, 415, 350);

        //---- label6 ----
        label6.setText("\u8bf7\u8f93\u5165\u8d2d\u4e70\u6570\u91cf\uff1a");
        label6.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label6);
        label6.setBounds(670, 465, 145, 40);
        contentPane.add(quantity);
        quantity.setBounds(825, 465, 240, 45);

        //---- label7 ----
        label7.setText("当前选择商品：");
        label7.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label7);
        label7.setBounds(170, 465, 145, 40);
        contentPane.add(productId);
        productId.setBounds(325, 465, 240, 45);

        //---- addProductBtn ----
        addProductBtn.setText("\u52a0\u5165\u8d2d\u7269\u8f66");
        addProductBtn.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(addProductBtn);
        addProductBtn.setBounds(375, 540, 120, 45);

        //添加商品进订单
        addProductBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                SaleDetailsDao saleDetailsDao = new SaleDetailsDao();
                String productName = productId.getText();
                int number = Integer.parseInt(quantity.getText());
                try {
                    Product product = productDao.getProduct(productName);//查找商品信息
                    int leftProduct = product.getStockQuantity();//商品剩余数量
                    if (number > leftProduct) {
                        JOptionPane.showMessageDialog(null,"商品库存不足！！！");
                        quantity.setText("");
                    } else {
                        OrderDetailNoUtil orderDetailNoUtil = new OrderDetailNoUtil();
                        String orderDetailNo = orderDetailNoUtil.randomOrderCode();//获取随机订单明细编号
                        SaleDetails saleDetails = new SaleDetails(orderDetailNo,orderNo,product.getProductId(),number);
                        saleDetailsDao.addSaleDetail(saleDetails);
                        table2.setModel(new SaleDetailsTableModel(orderNo));//刷新订单表
                        int index = 0;
                        ListModel<String> listModel = list1.getModel();
                        String productCategoryNameTemp = listModel.getElementAt(index);
                        ProductCategory productCategory = (ProductCategory) productCategoryList.get(index);
                        table1.setModel(new UserProductModel(productCategory.getCategoryId()));//刷新商品表
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        //---- payBtn ----
        payBtn.setText("\u4ed8\u6b3e");
        payBtn.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(payBtn);
        payBtn.setBounds(545, 540, 120, 45);

        payBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                UserDao userDao = new UserDao();
                try {
                    User user = userDao.login(userId);
                    float totalPrice = sale.getSaleTotalPrice();
                    float userPrice = user.getCardBalance();
                    if (totalPrice > userPrice) {
                        if (user.getIdentity().equals("教师")) {
                            //用户身份为教师可透支
                            JOptionPane.showMessageDialog(null,"亲爱的老师您的余额已不足，已为您启用教师卡透支服务！！！");
                            dispose();
                            UserMainFrame userMainFrame = new UserMainFrame(userId);
                        } else {
                            //用户身份为学生不能透支
                            JOptionPane.showMessageDialog(null,"你没钱啦！！！");
                            SaleDetailsDao saleDetailsDao = new SaleDetailsDao();
                            try {
                                List saleDetailsList = saleDetailsDao.getAppointSaleDeatils(orderNo);
                                for (int i = 0; i < saleDetailsList.size(); i++) {
                                    SaleDetails saleDetails = (SaleDetails) saleDetailsList.get(i);
                                    saleDetailsDao.deleteSaleDetails(saleDetails);
                                }
                                int index = 0;
                                ProductCategory productCategory = (ProductCategory) productCategoryList.get(index);
                                table1.setModel(new UserProductModel(productCategory.getCategoryId()));//刷新商品表
                                table2.setModel(new SaleDetailsTableModel(orderNo));
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(null,"付款成功！！");
                        dispose();
                        UserMainFrame userMainFrame = new UserMainFrame(userId);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        //---- cancelBtn ----
        cancelBtn.setText("取消订单");
        cancelBtn.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(cancelBtn);
        cancelBtn.setBounds(715, 540, 120, 45);

        cancelBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                SaleDetailsDao saleDetailsDao = new SaleDetailsDao();
                try {
                    List saleDetailsList = saleDetailsDao.getAppointSaleDeatils(orderNo);
                    for (int i = 0; i < saleDetailsList.size(); i++) {
                        SaleDetails saleDetails = (SaleDetails) saleDetailsList.get(i);
                        saleDetailsDao.deleteSaleDetails(saleDetails);
                    }
                    saleDao.deleteSale(sale);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                JOptionPane.showMessageDialog(null,"此次订单已删除！！");
                dispose();
                UserMainFrame userMainFrame = new UserMainFrame(userId);
            }
        });

        {
            // compute preferred size
            Dimension preferredSize = new Dimension();
            for(int i = 0; i < contentPane.getComponentCount(); i++) {
                Rectangle bounds = contentPane.getComponent(i).getBounds();
                preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
            }
            Insets insets = contentPane.getInsets();
            preferredSize.width += insets.right;
            preferredSize.height += insets.bottom;
            contentPane.setMinimumSize(preferredSize);
            contentPane.setPreferredSize(preferredSize);
        }
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel label1;
    private JScrollPane scrollPane1;
    private JList list1;
    private JLabel label2;
    private JScrollPane scrollPane2;
    private JTable table1;
    private JLabel label3;
    private JLabel label4;
    private JLabel label5;
    private JScrollPane scrollPane3;
    private JTable table2;
    private JLabel label6;
    private JTextField quantity;
    private JLabel label7;
    private JTextField productId;
    private JButton addProductBtn;
    private JButton payBtn;
    private JButton cancelBtn;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
    public static void main(String[] args) throws Exception {
        BrowseProductFrame browseProductFrame = new BrowseProductFrame("userId");
        LocalDate currentDate = LocalDate.now();
    }
}
